<template>
  <el-container class="layout-container-demo" style="height: 100vh">
    <el-dialog v-model="dialogFormVisible" title="创建地址" width="600">
      <el-form :model="addressForm" ref="addressFormRef" :rules="rules" status-icon>
        <el-form-item label="收货人" :label-width="formLabelWidth" prop="name">
          <el-input v-model="addressForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="省市区" :label-width="formLabelWidth">
          <div>
            <el-cascader v-model="choosePosition" :options="provinceList" :props="props" @change="handleChange" />
            <el-form-item :label-width="formLabelWidth" prop="provinceId"></el-form-item>
            <el-form-item :label-width="formLabelWidth" prop="cityId"></el-form-item>
            <el-form-item :label-width="formLabelWidth" prop="districtId"></el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="位置" :label-width="formLabelWidth" prop="position">
          <el-input v-model="addressForm.position" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phoneNumber">
          <el-input v-model="addressForm.phoneNumber" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="resetForm(addressFormRef)">
            取消
          </el-button>
          <el-button type="primary" @click="CUAddress(addressFormRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>
  
<script lang="ts" setup>
import { createAddressByJwt, getAddressByIdAndJwt, editAddressByIdAndJwt } from "../../api/address/"
import { getPlaceByJSON } from "../../api/places/"
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
// import { place } from '../api/object/'


// 要编辑的地址的id 
// !当为0时调用新建地址方法 非0是调用编辑地址方法
const id = ref(0);
//打开本AddressCU页
const dialogFormVisible = ref(false)
const openDialog = (addressId: number) => {
  dialogFormVisible.value = true
  id.value = addressId
}
defineExpose({
  openDialog
})

// 指定字段宽度属性
const formLabelWidth = '140px'
// 指定地址悬浮展开属性
const props = {
  expandTrigger: 'hover' as const,
}

//地址多级联选择 通过JSON引入
let provinceList = ref([])
const getPlaceByJSONResult = getPlaceByJSON()
getPlaceByJSONResult.then((res) => {
  provinceList.value = res.data
})
//地址多级联选择Ref
const choosePosition = ref([])

// 地址表单
interface addressType {
  id: number
  name: string,
  provinceId: number,
  cityId: number,
  districtId: number,
  position: string,
  phoneNumber: number,
}
const addressFormRef = ref<FormInstance>()
//创建地址表单数据
const addressForm = reactive<addressType>({
  id: 0,
  name: '',
  provinceId: 0,
  cityId: 0,
  districtId: 0,
  position: '',
  phoneNumber: 0,
})
const rules = reactive<FormRules<addressType>>({
  name: [
    { required: true, message: '请输入发货/收货人', trigger: 'blur' },
    { type: 'string', min: 2, max: 10, message: '长度2-10', trigger: 'blur' },
  ],
  provinceId: [
    { required: true, message: '请选择省', trigger: 'blur' },
    { type: 'number', min: 1, message: '长度大于1', trigger: 'blur' },
    // { pattern: /(^(?!0$).*)/, message: '请选择省', trigger: 'change' }

  ],
  cityId: [
    { required: true, message: '请选择市', trigger: 'blur' },
    { type: 'number', min: 1, message: '长度大于1', trigger: 'blur' },
    // { pattern: /(^(?!0$).*)/, message: '请选择市', trigger: 'change' }

  ],
  districtId: [
    { required: true, message: '请选择区', trigger: 'blur' },
    { type: 'number', min: 1, message: '长度大于1', trigger: 'blur' },
    // { pattern: /(^(?!0$).*)/, message: '请选择区', trigger: 'change' }

  ],
  position: [
    { required: true, message: '请输入位置', trigger: 'blur' },
    { type: 'string', min: 3, max: 10, message: '长度3-10', trigger: 'blur' },
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { type: 'number', min: 11, max: 15, message: '长度11-15数字', trigger: 'blur' },
  ],

})
// 当多级联选择器变化时将值赋值给地址表单
const handleChange = (value) => {
  addressForm.provinceId = value[0]
  addressForm.cityId = value[1]
  addressForm.districtId = value[2]
}
// 根据选择的订单获取值添加表单页面
watch(id, (newVal, oldVal) => {
  if (id.value != 0) {
    const getAddressByIdResult = getAddressByIdAndJwt({ id: newVal })
    getAddressByIdResult.then((res) => {
      if (res.code === 200) {
        //更改表单数据
        addressForm.id = res.data.id
        addressForm.name = res.data.name
        addressForm.provinceId = res.data.provinceId
        addressForm.cityId = res.data.cityId
        addressForm.districtId = res.data.districtId
        addressForm.position = res.data.position
        addressForm.phoneNumber = res.data.phoneNumber
        // 更改多级联选择器数据
        choosePosition.value[0] = res.data.provinceId
        choosePosition.value[1] = res.data.cityId
        choosePosition.value[2] = res.data.districtId

      } else {
        return ElMessage({
          showClose: true,
          message: res.message,
          type: 'error',
        })
      }
    })
  }
}, {
  // 深度监听
  deep: true,
  // 监听对象初次加载时也调用一次方法体
  // immediate: true
})
// CU地址
const CUAddress = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (addressForm.districtId == 0 || addressForm.provinceId == 0 || addressForm.cityId == 0) {
      return ElMessage({
        showClose: true,
        message: "请选择省市区",
        type: 'error',
      })
    }
    if (valid) {
      if (id.value == 0) {
        const createAddressResult = createAddressByJwt(addressForm)
        createAddressResult.then((res) => {
          if (res.code === 200) {
            dialogFormVisible.value = false
            return ElMessage({
              showClose: true,
              message: "创建地址成功",
              type: 'success',
            })
          } else {
            return ElMessage({
              showClose: true,
              message: res.message,
              type: 'error',
            })
          }
        })
      } else {
        const createAddressResult = editAddressByIdAndJwt(addressForm)
        createAddressResult.then((res) => {
          if (res.code === 200) {
            dialogFormVisible.value = false
            return ElMessage({
              showClose: true,
              message: "编辑地址成功",
              type: 'success',
            })
          } else {
            return ElMessage({
              showClose: true,
              message: res.message,
              type: 'error',
            })
          }
        })
      }
    } else {
      return ElMessage({
        showClose: true,
        message: '请检查参数',
        type: 'error',
      })
    }
  })
}

//页面清空返回
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value = false
}

</script>
  
<style scoped>
.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}

.layout-container-demo .el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}

.layout-container-demo .el-menu {
  border-right: none;
}

.layout-container-demo .el-main {
  padding: 0;
}

.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
}
</style>
  